<?php

class Register_User_API_Endpoint {

    public function __construct() {
        add_filter('query_vars', array($this, 'add_query_vars'), 0);
        add_action('parse_request', array($this, 'sniff_requests'), 0);
        add_action('init', array($this, 'add_endpoint'), 0);
    }

    /** Add public query vars
     * 	@param array $vars List of current public query vars
     * 	@return array $vars 
     */
    public function add_query_vars($vars) {
        $vars[] = '__api';
        $vars[] = 'name';
        $vars[] = 'ruc';
        $vars[] = 'rubro';
        $vars[] = 'subrubro';
        $vars[] = 'product';
        $vars[] = 'counter';
        $vars[] = 'email';
        $vars[] = 'action';
        return $vars;
    }

    /** Add API Endpoint
     * 	This is where the magic happens - brush up on your regex skillz
     * 	@return void
     */
    public function add_endpoint() {
        add_rewrite_rule('^api/register/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)/(.*?)/(.*)/?', 'index.php?__api=1&action=fe_register&name=$matches[1]&ruc=$matches[2]&rubro=$matches[3]&subrubro=$matches[4]&product=$matches[5]&counter=$matches[6]&email=$matches[7]', 'top');
    }

    public function sniff_requests() {
        global $wp;

        if (isset($wp->query_vars['action']) && $wp->query_vars['action'] == "fe_register") {
            $this->handle_request();
            exit;
        }
    }

    /** Handle Requests
     * 	This is where we send off for an intense pug bomb package
     * 	@return void 
     */
    protected function handle_request() {
        global $wp;
        $user = $wp->query_vars['name'];
        $ruc = $wp->query_vars['ruc'];
        $rubro = $wp->query_vars['rubro'];
        $subrubro = $wp->query_vars['subrubro'];
        $product = $wp->query_vars['product'];
        $counter = $wp->query_vars['counter'];
        $email = $wp->query_vars['email'];
        //

        $user_data = array(
            'user_login' => $ruc,
            'user_name' => $user,
            'user_email' => $email,
            'user_pass' => wp_generate_password()  // When creating an user, `user_pass` is expected.
        );

        $user_id = wp_insert_user($user_data);

        if (!is_wp_error($user_id)) {
            
            global $wpdb;
            
            wp_update_user(array('ID' => $user_id, 'role' => 'company'));

            update_user_meta($user_id, 'name_profile', sanitize_text_field($user));
            update_user_meta($user_id, 'ruc_profile', sanitize_text_field($ruc));
            
            $current_year = date('Y');
            $current_month = date('n');
            
            $ending_year = $current_year;
            $ending_month = $current_month;
            if($current_month == 1){
                $ending_year = $ending_year - 1;
                $ending_month = 12;
            } else {
                $ending_month = $ending_month - 1;
            }
            
            $sector = sanitize_text_field($rubro);
            $subsector =sanitize_text_field($subrubro);
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_sector (user_id, sector_id, subsector_id, year, month) 
                        values (%d, %d, %d, %d, %d)", $user_id, $sector, $subsector, $y, $m));
                }
            }
            
            $product = sanitize_text_field($product);
            for($y = 2010; $y <= $ending_year; $y++){
                $end_month = $y < $ending_year ? 12 : $ending_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_product (user_id, product, year, month) 
                        values (%d, '', %d, %d)", $user_id, $y, $m));
                }
            }
            $wpdb->query($wpdb->prepare("insert into bpa_registry_product (user_id, product, year, month) 
                        values (%d, %s, %d, %d)", $user_id, $product, $current_year, $current_month));
            
            $workers = sanitize_text_field($counter);
            for($y = 2010; $y <= $ending_year; $y++){
                $end_month = $y < $ending_year ? 12 : $ending_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_workers (user_id, year, month, number) 
                        values (%d, %d, %d, 0)", $user_id, $y, $m));
                }
            }
            $wpdb->query($wpdb->prepare("insert into bpa_registry_workers (user_id, year, month, number) 
                        values (%d, %d, %d, %d)", $user_id, $current_year, $current_month, $workers));
            
            $types = $wpdb->get_results("select t.id as type_id, st.id as subtype_id from bpa_consumption_type t left join bpa_consumption_subtype st on t.id = st.type_id");
            
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    foreach($types as $type){
                        $type_id = $type->type_id;
                        $subtype_id = $type->subtype_id == null ? 0 : $type->subtype_id;
                        $wpdb->query($wpdb->prepare(
                        "insert into bpa_registry_consumption (user_id, type_id, subtype_id, year, month, quantity, price) 
                        values (%d, %d, %d, %d, %d, %d, %d)", $user_id, $type_id, $subtype_id, $y, $m, 0, 0));
                    }
                }
            }
            
            $wpdb->query($wpdb->prepare(
                        "insert into bpa_inventory_user(user_id, item_id, quantity) 
                        select %d, id, 0 from bpa_inventory_item where custom = 0", $user_id));

            wp_new_user_notification($user_id, $user_data["user_pass"]);

            $this->send_response('OK', json_decode($user_id));
        } else {
            $this->send_response('Error');
        }
    }

    /** Response Handler
     * 	This sends a JSON response to the browser
     */
    protected function send_response($msg, $user = '') {
        $response['message'] = $msg;
        if ($user)
            $response['user'] = $user;
        header('content-type: application/json; charset=utf-8');
        echo json_encode($response) . "\n";
        exit;
    }

}

new Register_User_API_Endpoint();